package com.guodi.common.http;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;

import java.io.IOException;

/**
 * http请求工具类
 * Created by ks on 2020/11/26.
 */
public class HttpClient {

    public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");

    private ObjectMapper mapper = new ObjectMapper();

    private OkHttpClient httpClient = null;

    public HttpClient(OkHttpClient httpClient){
        this.httpClient = httpClient;
    }

    public String httpGet(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = this.httpClient.newCall(request).execute();
        return response.body().string(); // 返回的是string 类型，json的mapper可以直接处理
    }

    public String httpPost(String url, String json) throws IOException {
        RequestBody requestBody = RequestBody.create(JSON,json.getBytes());

        Request request =new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = this.httpClient.newCall(request).execute();
        return response.body().string();
    }

    public Object transform(String str) throws Exception{
        return mapper.readValue(str, new TypeReference<Object>(){});
    }

}
